import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
/**
 * 获取用户菜单权限和按钮权限
 * @param {*} routes
 * @param {*} roles
 * @returns
 */
export function getUrl(item, menuCodes, funcCodes) {
  item.map(x => {
    if (x.type === 1) {
      menuCodes.push(x.url)
    } else if (x.type === 2) {
      funcCodes.push(x.url)
    }
  })
}

export function auth(permissions, commit) {
  let menuCodes = []
  let funcCodes = []
  getUrl(permissions, menuCodes, funcCodes)
  // eslint-disable-next-line no-undef
  menuCodes = Array.from(new Set(menuCodes))
  // eslint-disable-next-line no-undef
  funcCodes = Array.from(new Set(funcCodes))
  commit('SET_MENU_CODES', menuCodes)
  commit('SET_FUNC_CODES', funcCodes)
  return menuCodes
}

const state = {
  menuCodes: [],
  funcCodes: [],
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_MENU_CODES: (state, codes) => {
    state.menuCodes = codes
  },
  SET_FUNC_CODES: (state, codes) => {
    state.funcCodes = codes
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, user) {
    return new Promise(resolve => {
      let accessedRoutes
      if (user.userInfo.is_admin === 1) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, auth(user.permissions, commit))
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
